package wafa.criterion;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import wafa.modelDocument.Content;
import wafa.modelDocument.Document;
import wafa.modelDocument.Family;
import wafa.modelDocument.Index;

import com.ibm.mm.sdk.common.DKConstant;
import com.ibm.mm.sdk.common.DKConstantICM;
import com.ibm.mm.sdk.common.DKDDO;
import com.ibm.mm.sdk.common.DKException;
import com.ibm.mm.sdk.common.DKLobICM;
import com.ibm.mm.sdk.common.DKNVPair;
import com.ibm.mm.sdk.common.DKParts;
import com.ibm.mm.sdk.common.DKRetrieveOptionsICM;
import com.ibm.mm.sdk.common.dkIterator;
import com.ibm.mm.sdk.common.dkResultSetCursor;
import com.ibm.mm.sdk.server.DKDatastoreICM;

public class CriteriaECMIBM {

	String stringQuery;
	String family;

	/**
	 * @return the query
	 */

	/**
	 * @return the family
	 */
	public String getFamily() {

		return family;
	}

	/**
	 * @param family
	 *            the family to set
	 */
	public void setFamily(String family) {
		this.family = family;

	}

	/**
	 * @return the stringQuery
	 */
	public String getStringQuery() {
		return stringQuery;
	}

	/**
	 * @param stringQuery
	 *            the stringQuery to set
	 */

	public void add(Criterion criterion) {
		if (stringQuery != null && !stringQuery.equals("")) {
			StringBuilder concatenation = new StringBuilder();
			concatenation.append("(");
			concatenation.append(stringQuery);
			concatenation.append(") AND ");
			concatenation.append(criterion.getCriterion());
			this.stringQuery = concatenation.toString();
		} else
			stringQuery = criterion.getCriterion();
	}
	
	
	List<Document> excuteQuery(String maximumNumberElement) throws DKException, Exception {
		StringBuilder concatenation = new StringBuilder();
		final String database = "serverged31";
		final String userName = "icmadmin";
		final String password = "icmadmin";
		final String schema = "SCHEMA=" + "ICMADMIN";
		DKNVPair options[] = new DKNVPair[3];
		DKDatastoreICM dsICM = new DKDatastoreICM();
		DKDDO ddo = null;
		List<Document> resultQuery = new ArrayList<Document>();
		Document document = null;
		Family family = new Family();
		family.setFamilyName(this.family);
		concatenation.append("/");
		concatenation.append(this.family);
		if (stringQuery != "") {
			concatenation.append("[");
			concatenation.append(stringQuery);
			concatenation.append("]");
		}
		this.stringQuery = concatenation.toString();
		System.out.println("--------------" + stringQuery);
		dsICM.connect(database, userName, password, schema);
		options[0] = new DKNVPair(DKConstant.DK_CM_PARM_MAX_RESULTS, maximumNumberElement);
		options[1] = new DKNVPair(DKConstant.DK_CM_PARM_RETRIEVE, new Integer(
				DKConstant.DK_CM_CONTENT_ATTRONLY));
		// Specify any Retrieval Options desired. Default is ATTRONLY.
		options[2] = new DKNVPair(DKConstant.DK_CM_PARM_END, null);

		dkResultSetCursor cursor = dsICM.execute(stringQuery,
				DKConstantICM.DK_CM_XQPE_QL_TYPE, options);
		while ((ddo = cursor.fetchNext()) != null) { // Get the next ddo &
														// stop when ddo ==
														// null.
			DKRetrieveOptionsICM retrOpts = DKRetrieveOptionsICM
					.createInstance(dsICM);
			retrOpts.baseAttributes(true); // Get Base Attributes
			retrOpts.partsList(true); // Get the parts
			retrOpts.resourceContent(true); // Get the document content
			ddo.retrieve(retrOpts.dkNVPair());
			document = new Document();
			document.setFamily(family);
			document.setDocumentId(ddo.getPidObject().pidString());

			// --------------------- Recover indexed ----------------------

			for (short dataid = 1; dataid <= ddo.dataCount(); dataid++) {
				if (ddo.getData(dataid) instanceof java.sql.Date) {

					document.getIndexes().add(
							new Index<Date>(ddo.getDataName(dataid), (Date) ddo
									.getData(dataid)));

				} else {

					document.getIndexes().add(
							new Index<Object>(ddo.getDataName(dataid), ddo
									.getData(dataid)));

				}
			}

			// --------- Retrieve content and attachment -------------

			short dataid = ddo.dataId(DKConstant.DK_CM_NAMESPACE_ATTR,
					DKConstant.DK_CM_DKPARTS);
			if (dataid == 0) {
				System.out.println("----");
			} else {
				DKParts dkParts = (DKParts) ddo.getData(dataid);

				// Print the list
				dkIterator iter = dkParts.createIterator(); // Create an
															// Iterator go
															// to through DDO
															// Collection.
				if (iter.more()) {
					DKDDO part = (DKDDO) iter.next(); // Move pointer to next
					// element & return that
					// object.
					DKLobICM dk = null;
					if (part instanceof DKLobICM) {
						dk = (DKLobICM) part;
						document.setContent(new Content(dk.getContent(),
								((DKLobICM) dk).getMimeType()));
					}
				}
				while (iter.more()) { // While there are items still to be
										// printed,
										// continue
					DKDDO part = (DKDDO) iter.next(); // Move pointer to next
														// element & return that
														// object.
					DKLobICM dk = null;
					if (part instanceof DKLobICM) {
						dk = (DKLobICM) part;
						document.getAttachments().add(
								new Content(dk.getContent(), ((DKLobICM) dk)
										.getMimeType()));
					}

				}
			}

			// -------- Adding document in the document list ---------

			resultQuery.add(document);
		}
		return resultQuery;
	}

}
